-module(gtp_bearer_dispatcher).
-include("protocol.hrl").

-behaviour(gen_server).
-export([start/0,start_link/0,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
-export([do/2]).
-define(SERVER,?MODULE).

do(packet_comming,Packet_Tuple) ->
	gen_server:cast(?SERVER,{packet_comming,Packet_Tuple}).
	
start()  ->
	case gen_server:start({local, ?SERVER}, ?MODULE, [], []) of 
	{ok,_} ->
		ok;
	{error,{already_started,Pid}} ->
		ok;
	{error,Reason} ->
		io:format("start ~s service failure with ~p~n",[?SERVER,Reason])
	end.
start_link() ->
	gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

init(_) ->
	io:format("~s start...~n",[?SERVER]),
	{ok,{runing,{}}}.

handle_call(_,_,State) ->
	{reply, {error,"no func define"}, State}.
	
handle_cast({packet_comming,P_Tuple},{runing,Sta}) ->
	[Udp_Info|[Ip_Info|_]] = P_Tuple#packet_tuple.context,
	Bearer_Server_IP = 
		case {Udp_Info#udp_protocol.source_port,Udp_Info#udp_protocol.dest_port} of
		{?GTP_C,_} ->
			Ip_Info#ip_protocol.source_ip;
		{_,?GTP_C} ->
			Ip_Info#ip_protocol.dest_ip;
		_ ->
			undefined 
		end,
	error_logger:info_msg("dispatch gtp-c for ~p",[Bearer_Server_IP]),
	gtp_bearer_server_sup:forward(Bearer_Server_IP,P_Tuple),
	{noreply,{runing,Sta}};
	
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.	
	